package com.fzdy.dataplatform.webutil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExcelReader {
    public static String getContentFromXls(FileInputStream fileIn) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook(fileIn);
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow rowColumn = sheet.getRow(0);
        if (rowColumn == null) return null;
        List<String> columnNameArr = new ArrayList<String>();
        for (int i = rowColumn.getFirstCellNum(); i < rowColumn.getLastCellNum(); i++) {
            HSSFCell cell = rowColumn.getCell(i);
            columnNameArr.add(cell.getStringCellValue());
        }
        JSONArray jsonArray = new JSONArray();
        for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) {
            JSONObject jsonObject = new JSONObject();
            HSSFRow row = sheet.getRow(i);
            for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
                HSSFCell cell = row.getCell(j);
                if (cell != null) {
                    if (cell.getCellType() == 1) {
                        jsonObject.put(columnNameArr.get(j), cell.getStringCellValue());
                    } else if (cell.getCellType() == 0) {
                        jsonObject.put(columnNameArr.get(j), (int) cell.getNumericCellValue());
                    } else {
                        jsonObject.put(columnNameArr.get(j), null);
                    }
                }
            }
            jsonArray.add(jsonObject);
        }
        return jsonArray.toString();
    }
}
